package com.capgemini.diabeo.model;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import com.capgemini.diabeo.model.Dish;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table DISH.
*/
public class DishDao extends AbstractDao<Dish, Long> {

    public static final String TABLENAME = "DISH";

    /**
     * Properties of entity Dish.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property Name = new Property(1, String.class, "name", false, "NAME");
        public final static Property Carbohydrate = new Property(2, Double.class, "carbohydrate", false, "CARBOHYDRATE");
        public final static Property Lipid = new Property(3, Double.class, "lipid", false, "LIPID");
        public final static Property Ig = new Property(4, Double.class, "ig", false, "IG");
        public final static Property Image = new Property(5, byte[].class, "image", false, "IMAGE");
        public final static Property IdCategory = new Property(6, Long.class, "idCategory", false, "ID_CATEGORY");
    };

    private DaoSession daoSession;

    private Query<Dish> category_DishListQuery;

    public DishDao(DaoConfig config) {
        super(config);
    }
    
    public DishDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'DISH' (" + //
                "'_id' INTEGER PRIMARY KEY ," + // 0: id
                "'NAME' TEXT NOT NULL ," + // 1: name
                "'CARBOHYDRATE' REAL," + // 2: carbohydrate
                "'LIPID' REAL," + // 3: lipid
                "'IG' REAL," + // 4: ig
                "'IMAGE' BLOB," + // 5: image
                "'ID_CATEGORY' INTEGER);"); // 6: idCategory
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'DISH'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, Dish entity) {
        stmt.clearBindings();
 
        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }
        stmt.bindString(2, entity.getName());
 
        Double carbohydrate = entity.getCarbohydrate();
        if (carbohydrate != null) {
            stmt.bindDouble(3, carbohydrate);
        }
 
        Double lipid = entity.getLipid();
        if (lipid != null) {
            stmt.bindDouble(4, lipid);
        }
 
        Double ig = entity.getIg();
        if (ig != null) {
            stmt.bindDouble(5, ig);
        }
 
        byte[] image = entity.getImage();
        if (image != null) {
            stmt.bindBlob(6, image);
        }
 
        Long idCategory = entity.getIdCategory();
        if (idCategory != null) {
            stmt.bindLong(7, idCategory);
        }
    }

    @Override
    protected void attachEntity(Dish entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public Dish readEntity(Cursor cursor, int offset) {
        Dish entity = new Dish( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.getString(offset + 1), // name
            cursor.isNull(offset + 2) ? null : cursor.getDouble(offset + 2), // carbohydrate
            cursor.isNull(offset + 3) ? null : cursor.getDouble(offset + 3), // lipid
            cursor.isNull(offset + 4) ? null : cursor.getDouble(offset + 4), // ig
            cursor.isNull(offset + 5) ? null : cursor.getBlob(offset + 5), // image
            cursor.isNull(offset + 6) ? null : cursor.getLong(offset + 6) // idCategory
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, Dish entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setName(cursor.getString(offset + 1));
        entity.setCarbohydrate(cursor.isNull(offset + 2) ? null : cursor.getDouble(offset + 2));
        entity.setLipid(cursor.isNull(offset + 3) ? null : cursor.getDouble(offset + 3));
        entity.setIg(cursor.isNull(offset + 4) ? null : cursor.getDouble(offset + 4));
        entity.setImage(cursor.isNull(offset + 5) ? null : cursor.getBlob(offset + 5));
        entity.setIdCategory(cursor.isNull(offset + 6) ? null : cursor.getLong(offset + 6));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(Dish entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(Dish entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "dishList" to-many relationship of Category. */
    public List<Dish> _queryCategory_DishList(Long idCategory) {
        synchronized (this) {
            if (category_DishListQuery == null) {
                QueryBuilder<Dish> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.IdCategory.eq(null));
                category_DishListQuery = queryBuilder.build();
            }
        }
        Query<Dish> query = category_DishListQuery.forCurrentThread();
        query.setParameter(0, idCategory);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getCategoryDao().getAllColumns());
            builder.append(" FROM DISH T");
            builder.append(" LEFT JOIN CATEGORY T0 ON T.'ID_CATEGORY'=T0.'_id'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected Dish loadCurrentDeep(Cursor cursor, boolean lock) {
        Dish entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        Category category = loadCurrentOther(daoSession.getCategoryDao(), cursor, offset);
        entity.setCategory(category);

        return entity;    
    }

    public Dish loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<Dish> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<Dish> list = new ArrayList<Dish>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<Dish> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<Dish> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
